package me.monster.lab.terimal;

import com.google.gson.Gson;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @description
 * @author: Created jiangjiwei in 2020/10/22 09:16
 */
class Entrance {
    public static final String queryLink = "https://www.androidos.net.cn/quicksearchfile";
    public static final String KEY_SEARCH = "searchtext=";
    public static final String KEY_VERSION = "sid=";
    public static final String COMMAND_LINK = "https://www.androidos.net.cn/android/";
    public static final String VALUE_DEFAULT_VERSION = "8.0.0_r4";

    public static final String COMMAND_HELP = "-h";
    public static final String COMMAND_VERSION = "-v";

    public static void main(String[] args) {
        if (args != null) {
//            System.out.println("Hello World " + args.length);
            parseArgs(args);
        } else {
            System.out.println("请输入 -h 查看帮助");
        }
    }

    private static void parseArgs(String[] args) {
        if (args.length == 1) {
            if (COMMAND_HELP.equals(args[0])) {
                System.out.println("-h 帮助");
                System.out.println("-v 版本号");
                System.out.println("示例 java -jar XXXX.jar {queryClassName}");
            } else if (COMMAND_VERSION.equals(args[0])) {
                System.out.println("1.0");
            } else {
                sendQueryRequest(args[0], VALUE_DEFAULT_VERSION);
            }
        }
    }

    private static void sendQueryRequest(String searchText, String valueDefaultVersion) {
        final String query = query(searchText, valueDefaultVersion);
        if ("".equals(query)) {
            System.out.println("服务器出错了");
        }
        final QueryResult queryResult = new Gson().fromJson(query, QueryResult.class);
        if (queryResult.success()) {
            System.out.println(queryResult.getSelectText());
            System.out.println("输入想要打开的文件序号（按回车结束)：");
            // 校验数字
            final int index = new Scanner(System.in).nextInt();
            String cmd = assembleCommand(valueDefaultVersion, queryResult.getPathByPosition(index - 1));
            if ("".equals(cmd)) {
                System.out.println("出错了");
            }
            System.out.println("将执行 " + cmd);
            runCommand(cmd);
        } else {
            System.out.println("服务器出错了\n" + query);
        }
    }

    private static String assembleCommand(String version, String filePath) {
        String command = "";
        if ("".equals(filePath)) {
            return command;
        }
        return "open " + COMMAND_LINK + version + "/xref/" + filePath;
    }

    private static void runCommand(String command) {
        Runtime run = Runtime.getRuntime();
        try {
            Process p = run.exec(command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static String query(String searchText, String version) {
        String response = "";
        HttpURLConnection connection = null;
        try {
            final String finalQueryLink = queryLink + "?" + KEY_SEARCH + searchText + "&" + KEY_VERSION + version;
            System.out.println("查询链接: " + finalQueryLink);
            URL url = new URL(finalQueryLink);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                //将响应流转换成字符串
                response = is2String(inputStream);//将流转换为字符串。
//                System.out.println("server response " + response);
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return response;
    }

    static String is2String(InputStream inputStream) {
        String message = "";
        try {
            byte[] data = new byte[1024];
            StringBuffer sb = new StringBuffer();
            int length = 0;
            while ((length = inputStream.read(data)) != -1) {
                String s = new String(data, 0, length, StandardCharsets.UTF_8);
                sb.append(s);
            }
            message = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }
}
